package com.lekang.quartz.task;

import java.util.Date;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.lekang.common.utils.DateUtils;
import com.lekang.le.domain.AppointmentRegistration;
import com.lekang.le.mapper.AppointmentRegistrationMapper;

/**
 * 预约状态更新定时器
 * 
 * @author system
 */
@Component("yuyue")
public class AppointmentStatusUpdateTask {
    private static final Logger log = LoggerFactory.getLogger(AppointmentStatusUpdateTask.class);

    @Autowired
    private AppointmentRegistrationMapper appointmentRegistrationMapper;

    /**
     * 定时检查预约状态
     * 每天8:00--19:00之间，每隔30分钟执行一次
     * 如果待上门数据的时间(当前时间-预约时间)超出1小时，则修改当前预约为已过期状态
     */
//    @Scheduled(cron = "1 0/30 8-19 * * ?")
    public void updateAppointmentStatus() {
        log.info("开始执行预约状态更新定时任务，执行时间：{}", DateUtils.getNowDate());

        // 创建查询条件，查询状态为"待上门"的预约记录
        AppointmentRegistration queryCondition = new AppointmentRegistration();
        queryCondition.setStatus("0");

        // 获取所有待上门的预约记录
        List<AppointmentRegistration> pendingAppointments = appointmentRegistrationMapper.selectAppointmentRegistrationList(queryCondition);

        if (pendingAppointments != null && !pendingAppointments.isEmpty()) {
            int updatedCount = 0;
            Date now = new Date();

            for (AppointmentRegistration appointment : pendingAppointments) {
                // 检查预约时间是否超过1小时
                if (appointment.getAppointmentTime() != null) {
                    long diffInMillis = now.getTime() - appointment.getAppointmentTime().getTime();
                    long diffInHours = diffInMillis / (60 * 60 * 1000);

                    // 如果超过1小时，则更新状态为"已过期"
                    if (diffInHours >= 1) {
                        appointment.setStatus("3");
                        appointmentRegistrationMapper.updateAppointmentRegistration(appointment);
                        updatedCount++;
                        log.info("更新预约ID：{} 状态为已过期，预约时间：{}", 
                                appointment.getId(), appointment.getAppointmentTime());
                    }
                }
            }

            log.info("预约状态更新定时任务执行完成，共更新{}条记录", updatedCount);
        } else {
            log.info("预约状态更新定时任务执行完成，没有需要更新的记录");
        }
    }
}
